<script>
    layui.use(['layer','form','table','laytpl','laydate','element','upload'], function(){
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var laytpl = layui.laytpl;
        var laydate = layui.laydate;
        var element = layui.element;
        var upload = layui.upload;
        var PageId = "{{request()->get('id', 0)}}";
        var UserId = "{{request()->get('user_id', 0)}}";
        var isView = "{{request()->get('is_view', false)}}";
        var Tier = 0;
        var UploadFiles = {};

        pageInit();

        //字典下拉框数据渲染
        function renderDicSelect() {
            return new Promise((resolve) => {
                getDicListByCodes({'diccode': ['JYZYLX']}, function (res){
                    if(res.code === 1) {
                        let data = res.data;

                        for(var k in data) {
                            let key = k.toLowerCase();
                            $('[data-role='+key+'List]').empty().append('<option value="">请选择</option>');
                            let d = data[k];
                            homework_type = d;
                            for (var i in d) {
                                $('[data-role='+key+'List]').append('<option value="' + d[i].itemcode + '">' + d[i].itemname + '</option>');
                            }
                        }

                        form.render();

                        resolve();
                    }
                });
            });
        }

        function renderHomeworkSelect(){
            $('[data-role=homework_typeList]').empty().append('<option value="">请选择</option>');
            for (var i in homework_type) {
                $('[data-role=homework_typeList]').append('<option value="' + homework_type[i].itemcode + '">' + homework_type[i].itemname + '</option>');
            }
        }

        async function pageInit() {
            await renderDicSelect();
            getActivityHomeworkInfo({activity_id: PageId, user_id: UserId}, function(res) {
                if(res.code === 1) {
                    let HomeworkData = res.data;

                    let hwShowTpl = hwDemo.innerHTML
                        ,hwShow = document.getElementById('homework-details');

                    laytpl(hwShowTpl).render(HomeworkData, function(html){
                        hwShow.innerHTML = html;
                    });
                    renderHomeworkSelect();
                    layui.each(HomeworkData, function(i, hw) {
                        if(hw) {
                            form.val('hwForm'+i, {
                                "type":hw.type,
                            });
                        }
                    });
                    form.render();

                    layui.each(HomeworkData, function(i, item) {
                        let moreInfo = item.more;
                        if(item.scale_id > 0) {
                            renderTable(item);
                        }
                        if(item.is_upload == 1) {
                            initUpload(item.id);
                            //文件
                            if(moreInfo && moreInfo.resource_set.length){
                                if(isView) {
                                    $(".layuik-upload").addClass("layui-hide");
                                    $(".layuik-uploaded").removeClass("layui-hide");
                                    fileShow(moreInfo.resource_set, item.id);
                                } else {
                                    layui.each(moreInfo.resource_set, function(i, d) {
                                        if(d.field == 'fj') {
                                            UploadFiles[item.id].push(d.file_origin);
                                            $('#fj-file'+item.id).val(JSON.stringify(UploadFiles[item.id]));

                                            $('#fj-uploader'+item.id).parent().find('.file-show').html('');
                                            for(i in UploadFiles[item.id]) {
                                                if(UploadFiles[item.id][i]) {
                                                    let fsHtml = '<div class="file-item"><span class="file-name">'+UploadFiles[item.id][i].file_name+'</span><span class="layui-icon layui-icon-close-fill" onClick="fileDelete('+i+', '+item.id+')"></span></div>';
                                                    $('#fj-uploader'+item.id).parent().find('.file-show').append(fsHtml);
                                                }
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    });

                    if(isView) {
                        $(".sub-button").addClass("layui-hide");
                        $(".layuik-upload").find('button').addClass("layui-hide");
                    }
                }
            });
        }

        // 文件显示
        function fileShow(files, id) {
            let showFiles = {};
            layui.each(files, function(i, d) {
                if(d.field) {
                    if (showFiles[d.field]) {
                        showFiles[d.field].push(d);
                    } else {
                        showFiles[d.field] = [d];
                    }
                }
            });

            layui.each(showFiles, function(f, d) {
                let fileShowTpl = fileShowDemo.innerHTML
                    ,fileShow = document.getElementById('file-show-'+f+id);

                laytpl(fileShowTpl).render(d, function(html){
                    fileShow.innerHTML = html;
                });
            });
        }

        // 渲染表格数据
        function renderTable(item = {}) {
            var Scale = item.scale_more;
            var Tier = Scale.tier_num;
            var TableData = item.score_info;
            var TableDetail = Scale.table_detail;

            if(Tier <= 0) return;

            var DetailTitle = {};
            for (i = 1; i <= Tier; i++) {
                DetailTitle[i] = convertToChinaNum(i);
            }

            var cols = [];
            var titleArr = [];
            cols.push({type: 'numbers', title: '序号', align: 'center'});
            for (let i in DetailTitle) {
                let filed = 'title'+i;
                let filedTitle = DetailTitle[i]+'级指标';

                titleArr.push(filed);
                cols.push({field: filed, title: filedTitle, align: 'center'});
            }
            cols.push({field: 'score_range', title: '参考分数', align: 'center', templet: function(d) {
                return d.max_score > 0 ? d.min_score + ' - ' + d.max_score + '分' : d.min_score + '分';
            }});
            if(isView) {
                cols.push({field: 'score', title: '评分', align: 'center'});
            } else {
                cols.push({field: 'score', title: '评分', align: 'center', edit: 'text'});
            }
            cols.push({field: 'score_hide', title: '评分', align: 'center', hide: true, templet: function(d) {
                let iptHtml = '<input type="hidden" id="hw-score'+d.id+'" name="score_info[]" required lay-verify="required" lay-reqText="评分没有完成！">';
                if(d.score) {
                    let iptVal = {'detail_id': d.id, 'score': d.score};

                    iptHtml = "<input type='hidden' id='hw-score"+d.id+"' name='score_info[]' value='"+JSON.stringify(iptVal)+"' required lay-verify='required' lay-reqText='评分没有完成！'>";
                }
                return iptHtml;
            }});

            table.render({
                elem: '#homework-table'+item.id
                ,data: TableData
                ,cellMinWidth: 80
                ,cols: [cols]
                ,id: 'homeworkTable'+item.id
                ,limit: TableData.length
                ,done: function(res, curr, count) {
                    layuiRowspan(titleArr, 1, item.id);
                }
            });
        }

        // 初始化文件上传
        function initUpload(id){
            if(!UploadFiles[id]) {
                UploadFiles[id] = [];
            }

            upload.render({
                elem: '#fj-uploader'+id
                ,url: "{{route('uploads.upload')}}" //此处配置你自己的上传接口即可
                ,accept: 'file' //普通文件
                ,multiple: true
                ,allDone: function(obj){ //当文件全部被提交后，才触发
                    if(obj.total == obj.successful) {
                        layer.msg('上传成功', {time: 1000});
                    } else {
                        layer.msg(obj.failed + '个文件上传失败！');
                    }
                }
                ,done: function(res){
                    UploadFiles[id].push(res.data);
                    $('#fj-file'+id).val(JSON.stringify(UploadFiles[id]));

                    $('#fj-uploader'+id).parent().find('.file-show').html('');
                    for(i in UploadFiles[id]) {
                        if(UploadFiles[id][i]) {
                            let fsHtml = '<div class="file-item"><span class="file-name">'+UploadFiles[id][i].file_name+'</span><span class="layui-icon layui-icon-close-fill" onClick="fileDelete('+i+', '+id+')"></span></div>';
                            $('#fj-uploader'+id).parent().find('.file-show').append(fsHtml);
                        }
                    }
                }
                ,error: function(index, upload){ //错误回调
                    console.log(index);
                }
            });
        }

        window.fileDelete = function (fk, id) {
            delete UploadFiles[id][fk];

            $('#fj-file'+id).val(JSON.stringify(UploadFiles[id]));
            $('#fj-uploader'+id).parent().find('.file-show').html('');
            for(i in UploadFiles[id]) {
                if(UploadFiles[id][i]) {
                    let fsHtml = '<div class="file-item"><span class="file-name">'+UploadFiles[id][i].file_name+'</span><span class="layui-icon layui-icon-close-fill" onClick="fileDelete('+i+', '+id+')"></span></div>';
                    $('#fj-uploader'+id).parent().find('.file-show').append(fsHtml);
                }
            }
        }

        //监听单元格编辑
        table.on('edit(homeworkTable)', function(obj){
            var elem = $(obj.elem)
                ,value = obj.value //得到修改后的值
                ,data = obj.data //得到所在行所有键值
                // ,field = obj.field //得到字段
                ,min_score = parseFloat(data.min_score)
                ,max_score = parseFloat(data.max_score);

            let score = parseFloat(value.replace(/^[.]{0,1}|[.]{0,1}$/g, ""));
            if (isNaN(score)) {
                obj.tr.find("#hw-score"+data.id).val('');
                return false;
            }
            if(min_score && max_score){
                //分数区间
                if(score >max_score){
                    layer.msg('评分不能超过'+max_score+'分');
                    $(this).val(max_score)
                    score = max_score;
                }
            }else if(min_score && !max_score){
                //单个分数
                if(score >min_score){
                    layer.msg('评分不能超过'+min_score+'分');
                    $(this).val(min_score)
                    score = min_score;
                }
            }else{
                layer.msg('参考分数出错');return false;
            }

            let val = {
                'detail_id': data.id,
                'score': score
            };

            obj.tr.find("#hw-score"+data.id).val(JSON.stringify(val));
        });

        var execRowspan = function (fieldName, index, tableId, flag) {
            // 1为不冻结的情况，左侧列为冻结的情况
            let fixedNode = index == "1" ? $("#homework-show"+tableId).find(".layui-table-body")[index - 1] : (index == "3" ? $(".layui-table-fixed-r") : $(".layui-table-fixed-l"));
            // 左侧导航栏不冻结的情况
            let child = $(fixedNode).find("td");
            let childFilterArr = [];
            // 获取data-field属性为fieldName的td
            for (let i = 0; i < child.length; i++) {
                if (child[i].getAttribute("data-field") == fieldName) {
                    childFilterArr.push(child[i]);
                }
            }
            // 获取td的个数和种类
            let childFilterTextObj = {};
            for (let i = 0; i < childFilterArr.length; i++) {
                let childText = flag ? childFilterArr[i].innerHTML : childFilterArr[i].textContent;
                if (childFilterTextObj[childText] == undefined) {
                    childFilterTextObj[childText] = 1;
                } else {
                    let num = childFilterTextObj[childText];
                    childFilterTextObj[childText] = num * 1 + 1;
                }
            }
            let canRowspan = true;
            let maxNum;//以前列单元格为基础获取的最大合并数
            let finalNextIndex;//获取其下第一个不合并单元格的index
            let finalNextKey;//获取其下第一个不合并单元格的值
            for (let i = 0; i < childFilterArr.length; i++) {
                (maxNum > 9000 || !maxNum) && (maxNum = $(childFilterArr[i]).prev().attr("rowspan") && fieldName != "8" ? $(childFilterArr[i]).prev().attr("rowspan") : 9999);
                let key = flag ? childFilterArr[i].innerHTML : childFilterArr[i].textContent;//获取下一个单元格的值
                let nextIndex = i + 1;
                let tdNum = childFilterTextObj[key];
                let curNum = maxNum < tdNum ? maxNum : tdNum;
                if (canRowspan) {
                    for (let j = 1; j <= curNum && (i + j < childFilterArr.length);) {//循环获取最终合并数及finalNext的index和key
                        finalNextKey = flag ? childFilterArr[i + j].innerHTML : childFilterArr[i + j].textContent;
                        finalNextIndex = i + j;
                        if ((key != finalNextKey && curNum > 1) || maxNum == j) {
                            canRowspan = true;
                            curNum = j;
                            break;
                        }
                        j++;
                        if ((i + j) == childFilterArr.length) {
                            finalNextKey = undefined;
                            finalNextIndex = i + j;
                            break;
                        }
                    }
                    childFilterArr[i].setAttribute("rowspan", curNum);
                    if ($(childFilterArr[i]).find("div.rowspan").length > 0) {//设置td内的div.rowspan高度适应合并后的高度
                        $(childFilterArr[i]).find("div.rowspan").parent("div.layui-table-cell").addClass("rowspanParent");
                        $(childFilterArr[i]).find("div.layui-table-cell")[0].style.height = curNum * 38 - 10 + "px";
                    }
                    canRowspan = false;
                } else {
                    childFilterArr[i].style.display = "none";
                }
                if (--childFilterTextObj[key] == 0 | --maxNum == 0 | --curNum == 0 | (finalNextKey != undefined && nextIndex == finalNextIndex)) {//||(finalNextKey!=undefined&&key!=finalNextKey)
                    canRowspan = true;
                }
            }
        }
        //合并数据表格行
        var layuiRowspan = function (fieldNameTmp, index, tableId, flag) {
            let fieldName = [];
            if (typeof fieldNameTmp == "string") {
                fieldName.push(fieldNameTmp);
            } else {
                fieldName = fieldName.concat(fieldNameTmp);
            }
            for (let i = 0; i < fieldName.length; i++) {
                execRowspan(fieldName[i], index, tableId, flag);
            }
        }

        //提交
        form.on('submit(sub)', function(data){
            let d = data.field;

            if('file' in d && !d['files[fj]']) {
                layer.msg('请上传附件！');
                return false;
            }
            d.activity_id = PageId;

            saveHomework(d, function(res){
                if(res.code == '1'){
                    layer.msg(res.msg,{icon: 6,time: 1000});
                }else{
                    layer.msg(res.msg, {icon: 5,shift : 6});
                }
            });

            return false;
        });
    });
</script>

<style>
    #homework-details .layui-card{margin-bottom: 20px;}
    #homework-details .layui-card-header{border-top: 1px solid #F6F6F6}
    .layui-checkbox-disabled[lay-skin=primary] span{color: #5f5f5f!important}
    .scale-content{margin-left: 50px;}
    .layui-table-view{border: 1px solid #ccc!important;}
    .score-item{margin-bottom: 0;}
    .score-tip{line-height: 42px;}
</style>

<!-- 量表维护信息 -->
<div class="layui-row">
    <div class="layui-panel" id="homework-details"></div>
</div>

<script type="text/html" id="hwDemo">
    @{{#  layui.each(d, function(index, item){ }}
    @{{#  if(item){ }}
    <div class="layui-card">
        <div class="layui-card-header">
            <h3>作业@{{index+1}}</h3>
        </div>
        <div class="layui-card-body">
            <form class="layui-form opt-form" action="" id="hw-form@{{index}}" lay-filter="hwForm@{{index}}">
                <div class="layuik-form-item">
                    <div class="layuik-inline">
                        <label class="layuik-form-label">参考材料：</label>
                        <div class="layuik-input-inline link-show">
                        @{{#  if(item.live_id){ }}
                            <input type="checkbox" name="live_id" lay-skin="primary" value="@{{item.live_id}}" title="@{{item.live.name}}" disabled checked>
                        @{{#  } }}
                        @{{#  layui.each(item.link_set, function(i, l){ }}
                            <input type="checkbox" name="link_id[]" lay-skin="primary" value="@{{l.id}}" title="@{{l.file_name}}" disabled checked>
                        @{{#  }); }}
                        </div>
                    </div>
                </div>
                @{{#  if(item.demand){ }}
                <div class="layuik-form-item">
                    <div class="layuik-inline">
                        <label class="layuik-form-label">作业要求：</label>
                        <div class="layuik-input-inline">
                            <textarea name="demand" id="" rows="3" class="layui-textarea" placeholder="请输入" disabled>@{{item.demand}}</textarea>
                        </div>
                    </div>
                </div>
                @{{#  } }}
                <div class="layuik-form-item">
                    <div class="layuik-inline">
                        <label class="layuik-form-label">类型：</label>
                        <div class="layuik-input-inline">
                            <select name="type" lay-filter="homework_typeList" data-role="homework_typeList" class="homework_type"></select>
                        </div>
                    </div>
                </div>
                @{{#  if(item.scale_id){ }}
                <div class="layuik-form-item score-item">
                    <div class="layuik-inline">
                        <label class="layuik-form-label">教师评价：</label>
                        <div class="layuik-input-inline">
                            <span class="score-tip redstar">#请进行打分评价</span>
                        </div>
                    </div>
                </div>
                <div class="layuik-form-item">
                    <div class="scale-content" id="homework-show@{{item.id}}">
                        <table id="homework-table@{{item.id}}" class="layui-table" lay-filter="homeworkTable"></table>
                    </div>
                </div>
                @{{#  } }}
                @{{#  if(item.is_upload == 1){ }}
                <div class="layuik-form-item layuik-columns-two">
                    <div class="layuik-inline">
                        <label class="layuik-form-label">上传附件：</label>
                        <div class="layuik-input-inline layuik-upload">
                            <button type="button" class="layui-btn layui-btn-normal" id="fj-uploader@{{item.id}}"><i class="layui-icon"></i>上传文件</button>
                            <div class="file-show"></div>
                            <input style="display:none" type="text" id="fj-file@{{item.id}}" name="files[fj]" value="">
                        </div>
                        <div class="layuik-input-inline layuik-uploaded layui-hide">
                            <div id="file-show-fj@{{item.id}}"></div>
                        </div>
                    </div>
                </div>
                @{{#  } }}
                @{{#  if(item.is_describe == 1){ }}
                <div class="layuik-form-item">
                    <div class="layuik-inline">
                        <label class="layuik-form-label">总结性描述：</label>
                        <div class="layuik-input-inline">
                            <textarea name="describe" id="" rows="3" class="layui-textarea" placeholder="请输入" lay-verify="required" lay-reqText="不能为空">
                                @{{#  if(item.more){ }}
                                @{{item.more.describe}}
                                @{{#  } }}
                            </textarea>
                        </div>
                    </div>
                </div>
                @{{#  } }}

                <div class="layui-row">
                    <div class="opt-area">
                        <button class="layui-btn layui-btn-normal sub-button" type="button" lay-submit lay-filter="sub">提交</button>
                        <input type="hidden" name="homework_id" value="@{{ item.id }}">
                        <input type="hidden" name="scale_id" value="@{{ item.scale_id }}">
                    </div>
                    <div id="score-inputs@{{item.id}}"></div>
                </div>
            </form>
        </div>
    </div>
    @{{#  } }}
    @{{#  }); }}
</script>
